﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TasksUI.Data
{
    public class TaskDAO
    {
        public TasksModel.TaskLibrary OpenLibrary(string path)
        {
            using (System.IO.StreamReader sr = System.IO.File.OpenText(path))
            {
                TasksModel.TaskLibrary tl = new TasksModel.TaskSerializer<TasksModel.TaskLibrary>().
                    Deserialize(sr);
                tl.OptimizeReferences();
                return tl;
            }
        }

        public void SaveLibrary(string path, TasksModel.TaskLibrary tl, Main owner)
        {
            TasksModel.TaskAuthor ta = tl.FindAuthorByName(Environment.UserName);
            if (ta == null)
            {
                ta = new TasksModel.TaskAuthor(Environment.UserName);
                tl.Authors.Add(ta);
                owner.AsM.AttachExplicit(ta);
            }
            string xml = new TasksModel.TaskSerializer<TasksModel.TaskLibrary>().Serialize(tl);
            System.IO.File.WriteAllText(path, xml);
        }

        public TasksModel.TaskLibrary DeepCopy(TasksModel.TaskLibrary tl)
        {
            TasksModel.TaskSerializer<TasksModel.TaskLibrary> ts =
                new TasksModel.TaskSerializer<TasksModel.TaskLibrary>();
            TasksModel.TaskLibrary _tl = ts.Deserialize(ts.Serialize(tl));
            _tl.OptimizeReferences();
            return _tl;
        }

        public void Merge(TasksModel.TaskLibrary tl, string path)
        {
            TasksModel.TaskLibrary lib = OpenLibrary(path);
            tl.MergeWith(lib);
        }

        public TasksModel.TaskLibrary CreateNewLibrary()
        {
            TasksModel.TaskLibrary tl = new TasksModel.TaskLibrary();
            tl.Statuses.SetupDefault();
            tl.Flags.SetupDefault();
            tl.CreatedAt = DateTime.UtcNow;
            tl.CreatedBy = new TasksModel.TaskAuthor(Environment.UserName);
            tl.Authors.Add(tl.CreatedBy);
            return tl;
        }
    }
}